﻿using Grow.Db.UnitOfWork;
using Grow.EventBus.Cap.PublisherHandler;
using Grow.Module.Service;

namespace Grow.EventBus.Cap.UnitOfWorkCommitAfter
{
    public class UnitOfWorkCommitAfter : IUnitOfWorkCommitAfter
    {
        private readonly IServiceContext _serviceContext;
        private readonly IEventPublisher _eventPublisher;
        private readonly IPublisherHandler _publisherHandler;

        public UnitOfWorkCommitAfter(IServiceContext serviceContext)
        {
            _serviceContext = serviceContext;
            _eventPublisher = _serviceContext.GetRequiredService<IEventPublisher>();
            _publisherHandler = _serviceContext.GetRequiredService<IPublisherHandler>();
        }
        public Task ExecuteAsync(CancellationToken cancellationToken)
        {
            Parallel.ForEach(_eventPublisher.GetPublisherEventDatas(), eventDataDto =>
            {
                _ = Task.Factory.StartNew(async () =>
                {
                    await _publisherHandler.ExecuteAsync(eventDataDto, cancellationToken);
                }, cancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Default);
            });
            return Task.CompletedTask;
        }


    }
}
